﻿Imports Persistencia
Imports System.IO
Public Class frmPrincipal

    Private Sub SetBackGroundColorOfMDIForm()
        Dim ctl As Control

        ' Loop through controls,  
        ' looking for controls of MdiClient type. 
        For Each ctl In Me.Controls
            If TypeOf (ctl) Is MdiClient Or
                TypeOf (ctl) Is Panel Or _
                TypeOf (ctl) Is Form Or
                TypeOf (ctl) Is PictureBox Then

                ' If the control is the correct type,
                ' change the color.
                ctl.BackColor = System.Drawing.Color.White
            End If
        Next

    End Sub

    Private Sub frmPrincipal_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim objConexaoBD As New Controle.ctrConexaoBD
        Dim objSeguranca As New Controle.ctrSeguranca
        Dim objAtualizacao As New AtualizaBD
        Dim objRegistro As New DSRegistro.Registro
        Dim frmConexaoBD As New frmConexaoBD
        Dim sLocalArquivo As String
        Dim sLocalAtl As String = ""
        Dim sStringConexao As String = ""
        Dim ioLerArquivo As StreamReader

        Try
            'Torna o formulário principal invisível para efeitos de validação de conexão, usuário e seleção de empresa
            Me.Visible = False

            SetBackGroundColorOfMDIForm()

            '===============================================================================
            '                   CONEXÃO COM BANCO DE DADOS                
            '===============================================================================
            Globais.LocalExecutavel = Application.StartupPath

            'O arquivo de conexão sempre deverá ficar na pasta do .exe e com o nome 'SQL.DS'
            sLocalArquivo = Globais.LocalExecutavel & "\" & "SQL.DS"
            sLocalAtl = Globais.LocalExecutavel & "\" & objAtualizacao.ArqAtualizacao

            'Se existe o arquivo no caminho indicado
            If File.Exists(sLocalArquivo) Then

                ioLerArquivo = New IO.StreamReader(sLocalArquivo, IO.FileMode.Open)

                sStringConexao = objSeguranca.descriptografar(ioLerArquivo.ReadLine)

                If objConexaoBD.testarConexao(sStringConexao) Then
                    'Se a conexão foi estabelecida seta a variável global de conexão
                    Globais.sStringConexaoBD = sStringConexao
                Else
                    MsgBox("Não foi possível estabelecer a conexão com o banco de dados.", MsgBoxStyle.Critical, Me.Text)
                    Me.Close()
                    Exit Sub
                End If

                ioLerArquivo.Close()

            Else

                'Se não existe o arquivo de conexão, abre o form de conexão
                With frmConexaoBD
                    .ShowDialog()
                    If frmConexaoBD.Sair Then
                        'Se o form de conexão foi fechado sem a conexão ser estabelecida
                        Me.Close()
                        Exit Sub
                    End If
                End With

            End If
            '===============================================================================
            '                   ATUALIZAÇÃO DE VERSÃO             
            '===============================================================================

            If (File.Exists(sLocalAtl)) Then
                With frmAtualiza
                    .Show()
                    objAtualizacao.CaminhoArquivo = sLocalAtl
                    objAtualizacao.Atualizacao(.ProgressBar)
                End With
                frmAtualiza.Close()
            End If

            '===============================================================================
            '                   LOGIN DE USUÁRIO              
            '===============================================================================

            'Quando estiver em modo DEBUG não será solicitado login de usuário e atribuído como '0' o IDUsuario global
#If Not Debug Then

            With frmAcesso
                .ShowDialog()
                If Not .Resultado Then
                    Me.Close()
                    Exit Sub
                End If
            End With
#Else
            Globais.iIDUsuario = 0
#End If
            '===============================================================================
            Me.Visible = True

        Catch ex As Exception
            MsgBox("Ocorreu um erro ao iniciar o sistema. " & ex.Message, MsgBoxStyle.Critical, Me.Text)
        End Try

    End Sub

    Private Sub AcessoBDToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AcessoBDToolStripMenuItem.Click
        Dim frm As New frmConsultaBd

        frm.MdiParent = Me
        frm.Show()
    End Sub

    Private Sub UsuáriosToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UsuáriosToolStripMenuItem.Click
        Dim frm As New frmUsuario

        frm.MdiParent = Me
        frm.Show()
    End Sub

    Private Sub SairToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SairToolStripMenuItem.Click
        End
    End Sub

    Private Sub LogoffMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LogToolStripMenuItem.Click

        frmAcesso = Nothing

        With frmAcesso
            .ShowDialog()
            If Not .Resultado Then
                Me.Close()
                Exit Sub
            End If
        End With

    End Sub

    Private Sub CadastroFuncionarioToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CadastroFuncionarioToolStripMenuItem.Click
        Dim frm As New frmProposta

        frm.MdiParent = Me
        frm.Show()
    End Sub

    Private Sub ConfiguracoesToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ConfiguracoesToolStripMenuItem.Click
        Dim frm As New frmConfiguracoes

        frm.MdiParent = Me
        frm.Show()
    End Sub

    Private Sub NovaToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs)
        Dim frm As New frmProposta

        frm.MdiParent = Me
        frm.Show()
    End Sub

    Private Sub ConsultaToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConsultaToolStripMenuItem2.Click
        Dim frm As New frmConsultaProposta

        frm.MdiParent = Me
        frm.Show()
    End Sub
End Class